/**
 * Copyright (C) 2013 DaiKit.com - daikit4gxt module (admin@daikit.com)
 *
 *         Project home : http://code.daikit.com/daikit4gxt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.daikit.daikit4gxt.client.ui.editor.advanced;

import java.util.logging.Logger;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Style.Float;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.IndexedPanel;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.GXTLogConfiguration;
import com.sencha.gxt.core.client.dom.XDOM;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.core.client.util.Size;
import com.sencha.gxt.widget.core.client.container.HasHeight;
import com.sencha.gxt.widget.core.client.container.HasMargins;
import com.sencha.gxt.widget.core.client.container.HasWidth;
import com.sencha.gxt.widget.core.client.container.HorizontalLayoutContainer;


/**
 *
 * Wrapper for {@link DkHorizontalLayoutContainer} changing positioning absolute to relative using float instead of
 * absolute left and top. This is order to have the content of children staying in the normal flow of the page. <br>
 * A layout container that lays out its children in a single row. The layout properties for each child are specified
 * using HorizontalLayoutData.
 *
 *
 * <p/>
 * Code Snippet:
 *
 * <pre>
 * HorizontalLayoutContainer c = new HorizontalLayoutContainer();
 * HorizontalLayoutData layoutData = new HorizontalLayoutData(100, 100, new Margins(5));
 * c.add(new TextButton(&quot;Button 1&quot;), layoutData);
 * c.add(new TextButton(&quot;Button 2&quot;), layoutData);
 * c.add(new TextButton(&quot;Button 3&quot;), layoutData);
 * RootPanel.get().add(c);
 * </pre>
 */
public class DkHorizontalLayoutContainer extends HorizontalLayoutContainer
{

	private static Logger logger = Logger.getLogger(HorizontalLayoutContainer.class.getName());

	private boolean secondPassRequired;

	//	/**
	//	 * {@link #doLayout()} wrapper to make it public
	//	 */
	//	public void doLayoutX()
	//	{
	//		doLayout();
	//	}

	@Override
	public void doLayout()
	{
		final Size size = getContainerTarget().getStyleSize();

		if (GXTLogConfiguration.loggingIsEnabled())
		{
			logger.finest(getId() + " doLayout size: " + size);
		}

		final int w = size.getWidth() - (isAdjustForScroll() ? XDOM.getScrollBarWidth() : 0);
		final int h = size.getHeight();
		int pw = w;

		final int count = getWidgetCount();

		// some columns can be percentages while others are fixed
		// so we need to make 2 passes
		for (int i = 0; i < count; i++)
		{
			final Widget c = getWidget(i);

			//			c.getElement().getStyle().setPosition(Position.ABSOLUTE);
			c.getElement().getStyle().setPosition(Position.RELATIVE); // CHANGED change position from absolute to relative

			double width = -1;

			final Object d = c.getLayoutData();
			if (d instanceof HasWidth)
			{
				width = ((HasWidth) d).getWidth();
			}

			if (width > 1)
			{
				pw -= width;
			}
			else if (width == -1)
			{
				if ((c instanceof HasWidgets || c instanceof IndexedPanel) && !secondPassRequired)
				{
					secondPassRequired = true;
					Scheduler.get().scheduleEntry(layoutCommand);
					return;
				}

				pw -= c.getOffsetWidth();
			}
			else if (width < -1)
			{
				pw -= w + width;
			}

			pw -= getLeftRightMargins(c); // total width minus all left/right margins
		}

		secondPassRequired = false;

		pw = pw < 0 ? 0 : pw;

		getElement().addClassName("clearfix");

		//		final int x = getContainerTarget().getPadding(Side.LEFT);
		//		final int sTop = getContainerTarget().getPadding(Side.TOP);

		for (int i = 0; i < count; i++)
		{
			final Widget c = getWidget(i);
			final Margins widgetMargins = getMargins(c); // ADDED
			//			c.getElement().getStyle().setMargin(0, Unit.PX);

			if (widgetMargins == null)
			{
				c.getElement().getStyle().setMargin(0, Unit.PX); // BEFORE THERE WAS ONLY THIS LINE
			}
			else
			{
				c.getElement().getStyle().setMarginTop(widgetMargins.getTop(), Unit.PX);
				c.getElement().getStyle().setMarginRight(widgetMargins.getRight(), Unit.PX);
				c.getElement().getStyle().setMarginBottom(widgetMargins.getBottom(), Unit.PX);
				c.getElement().getStyle().setMarginLeft(widgetMargins.getLeft(), Unit.PX);
			}

			double width = -1;
			double height = -1;

			final Object d = c.getLayoutData();
			if (d instanceof HasWidth)
			{
				width = ((HasWidth) d).getWidth();
			}
			if (d instanceof HasHeight)
			{
				height = ((HasHeight) d).getHeight();
			}

			if (height >= 0 && height <= 1)
			{
				height = height * h;
			}
			else if (height < -1)
			{
				height = h + height;
			}

			if (width >= 0 && width <= 1)
			{
				width = width * pw;
			}
			else if (width < -1)
			{
				width = w + width;
			}

			applyLayout(c, (int) Math.floor(width), (int) Math.floor(height));

			//			c.getElement().getStyle().setWidth(width, Unit.PX); // ADDED
			//			if (height > 0)
			//			{
			//				c.getElement().getStyle().setHeight(height, Unit.PX); // ADDED
			//			}
			c.getElement().getStyle().setFloat(Float.LEFT);

			//			final int tx = x;
			//			final int ty = sTop;
			//			final int tw = (int) Math.floor(width);
			//			final int th = (int) Math.floor(height);

			//			Margins m = null;
			//			if (d instanceof HasMargins)
			//			{
			//				m = ((HasMargins) d).getMargins();
			//				if (m != null)
			//				{
			//					tx += m.getLeft();
			//					ty += m.getTop();
			//					if (th != -1)
			//					{
			//						th -= m.getTop();
			//						th -= m.getBottom();
			//					}
			//				}
			//			}
			//
			//									applyLayout(c, new Rectangle(tx, ty, tw, th));

			//			if (tw == -1)
			//			{
			//				tw = c.getOffsetWidth();
			//			}
			//
			//			x += tw + (m != null ? (m.getLeft() + m.getRight()) : 0);
		}
	}

	private Margins getMargins(final Widget w)
	{
		final Object data = w.getLayoutData();
		Margins margins = null;
		if (data instanceof HasMargins)
		{
			margins = ((HasMargins) data).getMargins();
		}
		return margins;
	}
}
